﻿ 
using Microsoft.Extensions.Logging;
using SHKF.B2C.MeiTuanShanGou.BLL; 
using SHKF.B2C.Hosted;
using SHKF.B2C.MeiTuanShanGou.Model.Dto.Token;
using SHKF.B2C.MeiTuanShanGou.Model.Entity;
using SHKF.B2C.MeiTuanShanGou.Network;
using SHKF.B2C.Model;
using SHKF.B2C.Model.Dto;
using System;
using System.Threading.Tasks;
 

namespace SHKF.B2C.MeiTuanShanGou.Service.Controllers
{
    public class Base2Controller : HostedController
    {
        protected readonly HttpClientMeiTuanShanGou httpClientMeiTuanShanGou;
        private readonly TokenMtsgBLL tokenMtsgBLL;
        private int tokenOffice = 1; //一小时误差

        public Base2Controller(
            IServiceProvider serviceProvider,
            ILogger<Base2Controller> logger) : base(serviceProvider, logger)
        {
            this.tokenMtsgBLL = (TokenMtsgBLL)serviceProvider.GetService(typeof(TokenMtsgBLL));
            this.httpClientMeiTuanShanGou = (HttpClientMeiTuanShanGou)serviceProvider.GetService(typeof(HttpClientMeiTuanShanGou));
        }

        protected async Task<TokenMeiTuanDto> GetMtsgToken(long app_poi_code)
        {
            TokenMeiTuanDto dto = new TokenMeiTuanDto();
            DateTime now = DateTime.Now;

            try
            {
                long timestamp = DateTimeUtil.DateTimeToTimeStamp(now.AddHours(tokenOffice)); //一小时误差

                //数据库中获取 
                TokenMeiTuanEntity requestToken = this.tokenMtsgBLL.Get(app_poi_code);
                this.httpClientMeiTuanShanGou.app_poi_code = app_poi_code;

                if (requestToken == null || string.IsNullOrEmpty(requestToken.access_token))
                {
                    //如果数据中没有从接口中获取 
                    dto = await this.httpClientMeiTuanShanGou.GetToken(timestamp);
                    if (dto != null && !string.IsNullOrEmpty(dto.access_token))
                    {
                        SaveTokenToDB(app_poi_code, dto);
                    }
                    else if (dto.status != 0)
                    {
                        return dto;
                    }
                }
                else
                {
                    dto.access_token = requestToken.access_token;
                    dto.refresh_token = requestToken.refresh_token;
                    dto.expires_in = requestToken.expires;
                    dto.re_expires_in = requestToken.refresh_expires;
                    dto.status = 0;
                    dto.state = "";
                    dto.message = "";

                    this.setHttpToken(dto.access_token);

                    if (requestToken.expires <= timestamp) //如果access_token过期
                    {
                        //刷新    
                        if (requestToken.refresh_expires <= timestamp) //如果刷新时间也过期了,需要重新申请店铺，这是极端事件，需要手动去美团的平台操作
                        {
                            // dto.message = "授权已经过期，请联系商家重新授权,这是长期不用导致,同时删除它家美团的token";
                            dto.error = new Error() { code = -1, msg = "授权已经过期，请联系商家重新授权,这是长期不用导致,同时删除它家美团的token" };
                        }
                        else //如果refresh_token没有过期，重新刷新
                        {
                            long t = this.httpClientMeiTuanShanGou.GetTimeStamp();
                            dto = await this.httpClientMeiTuanShanGou.PostRefreshToken(requestToken.refresh_token, t);

                            //保存刷新的Token
                            SaveTokenToDB(app_poi_code, dto);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                dto = new TokenMeiTuanDto();
                dto.error = new Error() { code = -1, msg = ex.Message };
                dto.status = -1;
            }

            if (dto == null)
            {
                dto = new TokenMeiTuanDto();
                dto.error = new Error() { code = -1, msg = "Token不能为空" };
            }

            return dto;
        }

        private void SaveTokenToDB(long app_poi_code, TokenMeiTuanDto dto)
        {
            DateTime now = DateTime.Now;

            TokenMeiTuanEntity token = new TokenMeiTuanEntity();
            token.app_poi_code = app_poi_code;

            int day = (int)(dto.expires_in / 3600 / 24);
            int day_r = (int)(dto.re_expires_in / 3600 / 24);

            token.access_token = dto.access_token;
            token.expires = DateTimeUtil.DateTimeToTimeStamp(now.AddDays(day));

            token.refresh_token = dto.refresh_token;
            token.refresh_expires = DateTimeUtil.DateTimeToTimeStamp(now.AddDays(day_r));

            this.tokenMtsgBLL.Save(token);

            this.setHttpToken(token.access_token);
        }

        private void setHttpToken(string access_token)
        {
            this.httpClientMeiTuanShanGou.access_token = access_token;
        }


    }
}
